package com.goal98.team.services

import com.goal98.team.domain.Person
import com.goal98.team.domain.Activity
import com.goal98.grails.plugin.account.domain.Debit

class ActivityService {

    boolean transactional = true

    def accountService
    def myteamService
    def playerService

    def addCost(Activity activity, Debit debit) {

        def team = activity.team

        if(team.account == null){
            myteamService.openAccount(team)
        }
        def teamAccount = team.account
        teamAccount.addToTransactions(debit)
        teamAccount.debit(debit.amount)
        activity.addToCosts(debit)
        activity.save()
        debit.save()

    }

    def updateAttendPerson(def activityId, def personIds){
        def activity = Activity.get(activityId)

        Person.findAllByTeam(activity.team)?.each{Person player->
            player.removeFromActivityAttend(activity)
        }

        if(activity.actualPersonCount == 0)
            activity.actualPersonCount = personIds.size()
  
        personIds?.each{
            activity.addToPersonAttend(Person.get(it))
        }
    }

    def debitAttendPerson(Activity activity){
        activity.doneDebit = true

        def amount = activity.costOfEachPerson
        activity.personAttend?.each{Person player->
            playerService.debit(player, amount, "$activity")
        }

        activity.save()

    }

    def getUpcomingActivity(team){
        Activity.find("from Activity as a where a.team = ? and a.activityTime > ?", [team, new Date()])
    }

    def getPendingActivities(team){
        Activity.withCriteria{
            eq('team', team)
            eq('doneDebit', false)
            cache true
        }
//        Activity.findAll("from Activity as a where a.team = ? and a.doneDebit = ?", [team, false], [cache: true])
    }
}
